import 'dart:math' as math;
import 'package:azring/pages/status/daily_check_in/routes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../gen/assets.gen.dart';
import '../core/repository/default_api.dart';
import 'health_indicator_node.dart';
import '../core/controllers/ring_controller.dart';
import '../pages/status/status_logic.dart';
import '../pages/status/status_state.dart';

/// 健康仪表板组件
class HealthDashboard extends StatefulWidget {
  const HealthDashboard({super.key});

  @override
  State<HealthDashboard> createState() => _HealthDashboardState();
}

class _HealthDashboardState extends State<HealthDashboard>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _animation;

  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  // 获取状态控制器
  StatusLogic get statusController => Get.find<StatusLogic>();

  // 固定节点位置（事件记录固定占3个位置）
  List<Map<String, dynamic>> _getDynamicNodes() {
    // 总节点数 = 2情绪 + 3心率 + 4睡眠 + 3事件 + 4饮食 + 4活动 = 20个
    const totalNodes = 20;
    
    final center = Offset(187.5.w, 187.5.w);
    final radius = 140.w;
    List<Map<String, dynamic>> nodes = [];

    // 计算每个节点的角度
    // 事件节点（索引9-11）需要调整顺序：9和11互换
    for (int i = 0; i < totalNodes; i++) {
      int actualIndex = i;
      
      // 事件节点索引调整：让索引9的节点出现在索引11的位置，索引11的节点出现在索引9的位置
      if (i == 9) {
        actualIndex = 11;
      } else if (i == 11) {
        actualIndex = 9;
      }
      
      final angle = -math.pi / 2 + (actualIndex * 2 * math.pi / totalNodes);
      final x = center.dx + radius * math.cos(angle);
      final y = center.dy + radius * math.sin(angle);
      nodes.add({
        'position': Offset(x, y),
        'size': 20.0,
        'index': i,
      });
    }

    return nodes;
  }

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  // 获取节点的评分数据（事件固定3个位置）
  List<String> _getDynamicNodeScores() {
    final scoreData = statusController.state.conditionScoreData.value;
    if (scoreData == null) return [];

    List<String> scores = [];
    
    final validEvents = scoreData.eventScoreVOList
        .where((EventScoreVO e) => e.hasEventInfo)
        .toList();

    // 固定节点：情绪2个+心率3个
    scores.addAll([
      '${scoreData.pressureScore}',
      '${scoreData.emotionScore}',
      '${scoreData.oxygenScore}',
      '${scoreData.rateScore}',
      '${scoreData.hrvScore}',
    ]);

    // 固定节点：睡眠4个
    scores.addAll([
      '${scoreData.napScore}',
      '${scoreData.sleepDurationScore}',
      '${scoreData.sleepEfficiencyScore}',
      '${scoreData.deepSleepRatioScore}',
    ]);
    
    // 固定节点：事件3个（固定占位，从左到右填充）
    for (int i = 0; i < 3; i++) {
      if (i < validEvents.length) {
        final score = validEvents[i].recordScores;
        scores.add(score != null && score.isNotEmpty ? score : '--');
      } else {
        scores.add('--');
      }
    }

    // 固定节点：饮食4个+活动4个
    scores.addAll([
      '${scoreData.otherScore}',
      '${scoreData.dinnerScore}',
      '${scoreData.lunchScore}',
      '${scoreData.breakfastScore}',
      '${scoreData.bmiScore}',
      '${scoreData.caloriesScore}',
      '${scoreData.distanceScore}',
      '${scoreData.stepsScore}',
    ]);

    return scores;
  }

  // 获取节点颜色（固定位置）
  Color _getNodeColor(int index) {
    if (index < 2) {
      return const Color(0xFFFF6B9D); // 情绪 2个
    } else if (index < 5) {
      return const Color(0xFF5FC4D8); // 心率 3个
    } else if (index < 9) {
      return const Color(0xFF6FD195); // 睡眠 4个
    } else if (index < 12) {
      return const Color(0xFF5885FF); // 事件 3个（固定）
    } else if (index < 16) {
      return const Color(0xFFFFB366); // 饮食 4个
    } else {
      return const Color(0xFFB97EFF); // 活动 4个
    }
  }

  // 构建所有节点（只显示有数据的节点）
  List<Widget> _buildAllNodes() {
    final scoreData = statusController.state.conditionScoreData.value;
    if (scoreData == null) return [];
    
    final validEvents = scoreData.eventScoreVOList
        .where((EventScoreVO e) => e.hasEventInfo)
        .toList();
    
    final nodes = _getDynamicNodes();
    final scores = _getDynamicNodeScores();
    List<Widget> widgets = [];

    for (int i = 0; i < nodes.length && i < scores.length; i++) {
      final node = nodes[i];
      
      // 事件节点（索引9-11）：从左到右显示，只显示有数据的节点
      if (i >= 9 && i < 12) {
        final eventIndex = i - 9;
        // 如果当前位置超过事件数量，跳过
        if (eventIndex >= validEvents.length) {
          continue;
        }
      }
      
      widgets.add(
        HealthIndicatorNode(
          text: scores[i],
          color: _getNodeColor(i),
          position: node['position'],
          size: node['size'],
          isMainNode: false,
          onTap: () {},
        ),
      );
    }

    return widgets;
  }

  /// 刷新仪表盘数据
  Future<void> refreshDashboard() async {
    // 刷新身体状况评分数据
    await statusController.refreshConditionScoreData();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 仪表盘圆形部分
        SizedBox(
          width: 375.w,
          height: 375.w,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              // 连接线（最底层，在背景图片下面）
              Positioned.fill(
                child: IgnorePointer(
                  child: Obx(() => CustomPaint(
                    painter: _DashboardPainter(
                      nodes: _getDynamicNodes(),
                      scores: _getDynamicNodeScores(),
                      getNodeColor: _getNodeColor,
                      animation: _animation,
                      centerOffset: Offset(187.5.w, 187.5.w),
                    ),
                  )),
                ),
              ),
              // 背景图片 - score_bg (在连接线上面)
              Positioned.fill(
                child: Center(
                  child: Assets.status.scoreBg.image(
                    width: 375.w,
                    height: 375.w,
                    fit: BoxFit.contain,
                  ),
                ),
              ),
              // 仪表盘外围标签（环状排列）
              Positioned.fill(
                child: _OuterLabels(
                  dashboardSize: Size(375.w, 375.w),
                  centerOffset: Offset(187.5.w, 187.5.w),
                ),
              ),
              // 中心分数
              Positioned(
                top: 130.h,
                left: 0,
                right: 0,
                child: Center(
                  child: Obx(() {
                    final scoreData =
                        statusController.state.conditionScoreData.value;
                    final totalScore = scoreData?.totalScore ?? 0;

                    return Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: [
                        Text(
                          totalScore > 0 ? '$totalScore' : '--',
                          style: TextStyle(
                            fontSize: 54.sp,
                            fontWeight: FontWeight.w500,
                            color: const Color(0xffF9F8F7),
                            height: 1.0,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Padding(
                          padding: EdgeInsets.only(bottom: 2.h),
                          child: Text(
                            '分',
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w500,
                              color: const Color(0xffF9F8F7),
                              height: 1.0,
                            ),
                          ),
                        ),
                      ],
                    );
                  }),
                ),
              ),

              // 开启今日签按钮
              Positioned(
                top: 203.h,
                left: 0,
                right: 0,
                child: Center(
                  child: GestureDetector(
                    onTap: () async {
                      Get.dialog(
                        const Center(
                          child: CircularProgressIndicator(
                            color: Colors.white,
                          ),
                        ),
                        barrierDismissible: false,
                      );

                       try {
                        final result = await DefaultApi().addTodaySignPost(
                          deviceSn: ringController.getCurrentDeviceSn(),
                          isShowLoading: false,
                        );
                        Get.back();

                        if (result != null) {
                          Get.toNamed(DailyCheckInRoutes.dailyCheckIn,
                              arguments: result['data']);
                        } else {
                          Get.toNamed(DailyCheckInRoutes.dailyCheckIn);
                        }
                      } catch (e) {
                        Get.back();
                        Get.toNamed(DailyCheckInRoutes.dailyCheckIn);
                      }
                     
                    },
                    child: Container(
                      width: 110.w,
                      height: 40.h,
                      padding: EdgeInsets.symmetric(horizontal: 10.w),
                      decoration: BoxDecoration(
                        color: const Color(0xFFF9F8F7),
                        borderRadius: BorderRadius.circular(100.r),
                        boxShadow: [
                          BoxShadow(
                            color: const Color(0xFFFDF8F5).withValues(alpha: 0.54),
                            offset: const Offset(0, 0),
                            blurRadius: 11.2,
                            spreadRadius: 0,
                          ),
                        ],
                      ),
                      child: Center(
                        child: Text(
                          '开启今日签',
                          style: TextStyle(
                            fontSize: 15.sp,
                            fontFamily: 'ABeeZee',
                            color: const Color(0xFF050302),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),

              // 动态生成所有节点
              Obx(() => Stack(
                    clipBehavior: Clip.none,
                    children: _buildAllNodes(),
                  )),
            ],
          ),
        ),
        
        // 下方主节点分类
        SizedBox(height: 20.h),
        const _MainCategoryNodes(),
      ],
    );
  }
}

/// 绘制连接线的CustomPainter
class _DashboardPainter extends CustomPainter {
  final List<Map<String, dynamic>> nodes;
  final List<String> scores;
  final Color Function(int) getNodeColor;
  final Animation<double> animation;
  final Offset centerOffset;

  _DashboardPainter({
    required this.nodes,
    required this.scores,
    required this.getNodeColor,
    required this.animation,
    required this.centerOffset,
  }) : super(repaint: animation);

  @override
  void paint(Canvas canvas, Size size) {
    // 判断事件节点数量
    int validEventCount = 0;
    if (scores.length >= 12) {
      for (int i = 9; i < 12; i++) {
        if (scores[i] != '--') {
          validEventCount++;
        }
      }
    }
    
    for (int i = 0; i < nodes.length; i++) {
      // 事件节点（索引9-11）：只绘制有数据的节点连接线
      if (i >= 9 && i < 12) {
        final eventIndex = i - 9;
        if (eventIndex >= validEventCount) {
          continue; // 跳过没有数据的事件节点
        }
      }
      
      final node = nodes[i];
      final nodePos = node['position'] as Offset;
      final nodeSize = node['size'] as double;
      final color = getNodeColor(i);

      _drawLineFromCenter(canvas, centerOffset, nodePos, color, nodeSize);
    }
  }

  /// 绘制从中心到节点的连接线（向日葵样式，4-5条向内弯曲的曲线）
  void _drawLineFromCenter(
      Canvas canvas, Offset center, Offset nodePos, Color color, double nodeSize) {
    final nodeRadius = nodeSize / 2;
    final direction = (nodePos - center);
    final distance = direction.distance;
    final normalizedDirection = direction / distance;

    final end = nodePos - normalizedDirection * nodeRadius;

    final paint = Paint()
      ..color = color.withValues(alpha: 0.4)
      ..strokeWidth = 1.0
      ..style = PaintingStyle.stroke;

    // 绘制4-5条从中心分散到外面聚拢的曲线
    final lineCount = 5;
    final spreadAngle = 0.55; // 分散角度（弧度）
    
    for (int i = 0; i < lineCount; i++) {
      // 计算每条线的角度偏移
      final t = (i - (lineCount - 1) / 2) / (lineCount - 1); // -0.5 到 0.5
      final angleOffset = t * spreadAngle;
      
      // 计算起点方向（带角度偏移）
      final startAngle = math.atan2(direction.dy, direction.dx) + angleOffset;
      final startDirection = Offset(math.cos(startAngle), math.sin(startAngle));
      
      // 内侧线条从更靠近中心的位置开始（更长）
      // 外侧线条从较远的位置开始（较短）
      final startRadius = 50.0 + (1 - t.abs()) * 30.0; // 50-80之间
      final lineStart = center + startDirection * startRadius;
      
      // 终点聚拢到节点
      final lineEnd = end;
      
      // 使用二次贝塞尔曲线，控制点向中心方向偏移（向内弯曲）
      final midPoint = Offset(
        (lineStart.dx + lineEnd.dx) / 2,
        (lineStart.dy + lineEnd.dy) / 2,
      );
      
      // 控制点向中心方向偏移，产生向内的弧度
      final toCenter = center - midPoint;
      final controlPoint = midPoint + toCenter * 0.15; // 向中心偏移15%
      
      final path = Path();
      path.moveTo(lineStart.dx, lineStart.dy);
      path.quadraticBezierTo(
        controlPoint.dx,
        controlPoint.dy,
        lineEnd.dx,
        lineEnd.dy,
      );
      
      canvas.drawPath(path, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 仪表盘外围文字标签
class _OuterLabels extends StatelessWidget {
  final Size dashboardSize;
  final Offset centerOffset;
  const _OuterLabels({
    required this.dashboardSize,
    required this.centerOffset,
  });

  @override
  Widget build(BuildContext context) {
    final statusController = Get.find<StatusLogic>();

    return Obx(() {
      final scoreData = statusController.state.conditionScoreData.value;
      final validEvents = scoreData?.eventScoreVOList
          .where((EventScoreVO e) => e.hasEventInfo)
          .toList() ?? [];

      // 定义所有标签（固定19个）
      final List<String> labels = [];
      
      // 固定：情绪2个+心率3个
      labels.addAll(['压力评估', '情绪评估', '血氧健康', '静息心率', '心率变异性']);
      
      // 固定：睡眠4个
      labels.addAll(['小睡得分', '睡眠时长', '睡眠效率', '深睡比例']);
      
      // 固定：事件3个
      for (int i = 0; i < 3; i++) {
        if (i < validEvents.length) {
          labels.add(validEvents[i].eventInfo ?? '未记录');
        } else {
          labels.add(''); // 空位不显示标签
        }
      }
      
      // 固定：饮食4个+活动4个
      labels.addAll(['其他饮食', '晚餐计分', '午餐计分', '早餐计分', '体脂状态', '热量消耗', '运动距离', '活动步数']);

      return Stack(
        clipBehavior: Clip.none,
        children: _buildCircularLabels(labels, validEvents.length),
      );
    });
  }

  /// 构建环状排列的标签（手动定位每个标签）
  List<Widget> _buildCircularLabels(List<String> labels, int validEventCount) {
    List<Widget> widgets = [];
    
    // 手动定义每个标签的位置和旋转角度（从顶部开始顺时针）
    // 格式：[left, top, rotation]
    final List<List<double>> positions = [
      // 索引0-1：情绪节点（顶部偏左）
      [165.w, 10.h, 85],  // 0: 压力评估
      [220.w, 17.h, 105],  // 1: 情绪评估
      
      // 索引2-4：心率节点（顶部到右上）
      [265.w, 40.h, -60],  // 2: 血氧健康
      [305.w, 77.h, -45], // 3: 静息心率
      [330.w, 120.h, -30], // 4: 心率变异性
      
      // 索引5-8：睡眠节点（右上到右侧）
      [338.w, 175.h, 0], // 5: 小睡得分
      [330.w, 230.h, 20], // 6: 睡眠时长
      [305.w, 275.h, 35], // 7: 睡眠效率
      [270.w, 310.h, 55], // 8: 深睡比例
      
      // 索引9-11：事件节点（底部，固定3个位置）
      [125.w, 328.h, -65], // 9: 事件1
      [175.w, 340.h, -90], // 10: 事件2
      [225.w, 328.h, -115], // 11: 事件3
      
      // 索引12-15：饮食节点（底部到左下）
      [-2.w, 175.h, 0], // 12: 其他饮食
      [5.w, 230.h, -20], // 13: 晚餐计分
      [25.w, 275.h, -35], // 14: 午餐计分
      [65.w, 315.h, -55], // 15: 早餐计分
      
      // 索引16-18：活动节点（左下到左上）
      [5.w, 130.h, 15], // 16: 体脂状态
      [30.w, 77.h, 40], // 17: 热量消耗
      [65.w, 40.h, 55], // 18: 运动距离
      [115.w, 17.h, 75], // 19: 活动步数
    ];

    for (int i = 0; i < labels.length && i < positions.length; i++) {
      final label = labels[i];
      
      // 事件节点（索引9-11）：只显示有数据的标签
      if (i >= 9 && i < 12) {
        final eventIndex = i - 9;
        if (eventIndex >= validEventCount || label.isEmpty) {
          continue; // 跳过没有数据的事件标签
        }
      }
      
      final pos = positions[i];
      
      widgets.add(
        Positioned(
          left: pos[0],
          top: pos[1],
          child: Transform.rotate(
            angle: pos[2] * math.pi / 180, // 转换为弧度
            child: Text(
              label,
              style: TextStyle(
                fontSize: 10.sp,
                color: const Color(0xFF9EA0A3),
                fontWeight: FontWeight.w300,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
      );
    }

    return widgets;
  }
}

/// 主分类节点（显示在仪表盘下方）
class _MainCategoryNodes extends StatelessWidget {
  const _MainCategoryNodes();

  @override
  Widget build(BuildContext context) {
    final statusController = Get.find<StatusLogic>();

    return Obx(() {
      final scoreData = statusController.state.conditionScoreData.value;
      
      print('DEBUG: scoreData = $scoreData');
      print('DEBUG: eventTotalScore = ${scoreData?.eventTotalScore}');

      final categories = [
        {
          'icon': Assets.status.eventChart,
          'label': '事件记录',
          'score': scoreData?.eventTotalScore ?? 0,
          'color': const Color(0xFF5885FF),
          'unit': '分',
        },
        {
          'icon': Assets.status.eatChart,
          'label': '饮食记录',
          'score': scoreData?.foodTotalScore ?? 0,
          'color': const Color(0xFFFFB366),
          'unit': '分',
        },
        {
          'icon': Assets.status.activityChart,
          'label': '活动代谢',
          'score': scoreData?.sportTotalScore ?? 0,
          'color': const Color(0xFFB97EFF),
          'unit': '分',
        },
        {
          'icon': Assets.status.emotionChart,
          'label': '情绪压力',
          'score': scoreData?.emotionalStressScore ?? 0,
          'color': const Color(0xFFFF6B9D),
          'unit': '分',
        },
        {
          'icon': Assets.status.hrChart,
          'label': '生命指标',
          'score': scoreData?.physicalSignsScore ?? 0,
          'color': const Color(0xFF5FC4D8),
          'unit': '分',
        },
        {
          'icon': Assets.status.sleepChart,
          'label': '睡眠质量',
          'score': scoreData?.sleepTotalScore ?? 0,
          'color': const Color(0xFF6FD195),
          'unit': '分',
        },
      ];

      return SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: categories.map((category) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: 4.w),
              child: _buildCategoryItem(
                icon: category['icon'] as AssetGenImage,
                label: category['label'] as String,
                score: category['score'] as int,
                color: category['color'] as Color,
                unit: category['unit'] as String,
              ),
            );
          }).toList(),
        ),
      );
    });
  }

  Widget _buildCategoryItem({
    required AssetGenImage icon,
    required String label,
    required int score,
    required Color color,
    required String unit,
  }) {
    return Column(
      children: [
        Container(
          width: 48.w,
          height: 25.h,
          decoration: BoxDecoration(
            color: color.withValues(alpha: 0.15),
            borderRadius: BorderRadius.circular(100.r),
            border: Border.all(
              color: color.withValues(alpha: 0.5),
              width: 0.5,
            ),
          ),
          child: Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.baseline,
              textBaseline: TextBaseline.alphabetic,
              children: [
                Text(
                  '$score',
                  style: TextStyle(
                    fontSize: 17.sp,
                    color: color,
                  ),
                ),
                Text(
                  unit,
                  style: TextStyle(
                    fontSize: 11.sp,
                    color: color.withValues(alpha: 0.8),
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ],
            ),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          label,
          style: TextStyle(
            fontSize: 10.sp,
            color: Colors.white.withValues(alpha: 0.7),
            fontWeight: FontWeight.w400,
          ),
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }
}